package com.mali.malibackendlog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mali.backendcommon.common.Result;
import com.mali.backendcommon.constant.AuthenticationConstant;
import com.mali.backendcommon.rpc.ProductService;
import com.mali.backendcommon.util.UserContext;
import com.mali.malibackendmodel.pojo.Operation;
import com.mali.malibackendlog.service.OperationService;
import com.mali.malibackendlog.mapper.OperationMapper;
import com.mali.malibackendmodel.pojo.User;
import com.mali.malibackendmodel.vo.OperationVO;
import com.mali.malibackendmodel.vo.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author 132993
* @description 针对表【operation(操作)】的数据库操作Service实现
* @createDate 2024-06-16 10:09:33
*/
@Service
public class OperationServiceImpl extends ServiceImpl<OperationMapper, Operation>
    implements OperationService{
    @Autowired
    private OperationMapper operationMapper;
    @Autowired
    private ProductService productService;


    @Override
    public Result<PageVO<OperationVO>> getLog(Long page, Long size, Long productId) {
        // 获取用户信息
        User user = UserContext.getUser();
        Long userId=user.getId();
        Integer role=user.getRole();
        if (role== AuthenticationConstant.ADMIN){
            // 验证权限
            boolean authority = productService.haveAuthority(productId, userId);
            if (!authority){
                return Result.error("没有权限访问");
            }
        }
        LambdaQueryWrapper queryWrapper=new LambdaQueryWrapper<Operation>().eq(Operation::getProductId, productId);
        Page<Operation> operationPage = new Page<>(page,size);
        operationMapper.selectPage(operationPage,queryWrapper);
        List<Operation> operations = operationPage.getRecords();
        if (operations==null || operations.size()==0){
            return Result.success();
        }
        List<OperationVO> operationVOList= new ArrayList<>();
        operations.stream().forEach(item->{
            OperationVO operationVO = new OperationVO();
            BeanUtils.copyProperties(item,operationVO);
            operationVOList.add(operationVO);
        });
        PageVO<OperationVO> pages = new PageVO<>();
        pages.setTotal(operationPage.getTotal());
        pages.setRecord(operationVOList);
        return Result.success(pages);
    }
}




